<template>
	<div class="searchPage">
		<!-- 回到上方按钮 -->
		<u-toast ref="uToast"></u-toast>
		<u-back-top :scroll-top="scrollTop"></u-back-top>
		<!-- 搜索框 -->
		<!-- <view>你搜索的关键词是：{{ searchKeyword }}</view> -->
		<view class="search-box">
			<view class="search-input">
				<text class="iconfont" @click="goToSearchPage"></text>
				<input type="text" v-model="searchKeyword" placeholder="请输入场馆名称" />
				<button class="search-btn" @click="executeSearch(searchKeyword,type)">搜索</button>
			</view>
		</view>
		<!-- 定位栏和分类栏 -->
		<view class="location-bar">
			<view class="location">
				<u-icon name="map" color="gray" size="18"></u-icon>
				<text style="color:gray; font-size: 13px;">{{ getRecommend }}</text>
				<u-icon name="arrow-right" color="gray" size="16"> </u-icon>
			</view>
			<view class="type" @click="toggleVenueTypesMenu">
				<!-- <text>分类</text> -->
				<text
					:style="{ color: type ? '#4A90E2' : 'gray', 'font-weight': type ? 'bold' : 'normal' } ">{{ selectedType || '分类' }}</text>
				<u-icon name="list-dot" color="gray" size="16"></u-icon>
			</view>
			<!-- <view class="notification">
				<text class="iconfont"></text>
			</view> -->
		</view>
		<!-- 场馆分类 -->
		<view v-if="isVenueTypesMenuVisible" class="venue-types-menu">
			<venueTypes :venueTypes="venueTypesData" layoutType="grid" />
		</view>
		<!-- <venueTypes :venueTypes="searchResults" :selectedType="selectedType" /> -->
		<!-- 场馆列表 -->
		<!-- 骨架屏 -->
		<view style="margin-top: 10px;" v-if="loading">
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
			<u-skeleton :loading="true" avatar avatarShape="square" avatarSize="88" title titleHeight="24"
				:animate="true" rows="2" rowsWidth="90%" class="skeleton-screen full-screen" style="margin-top: 0px;">
			</u-skeleton>
		</view>
		<!-- 场馆列表 -->
		<venueList :venueList="searchResults" v-if="!loading && venueListData.data.records.length > 0 " />
		<view v-if="!loading && venueListData.data.records.length === 0 ">没有找到相关场馆</view>
		<!-- <venueList :venueList="searchResults" v-if="venueListData.data.records.length > 0 " /> -->

		<!-- 场馆列表 -->
		<!-- <venueList :venueList="venueListData.data.records" v-else /> -->
		<!-- <view v-else>没有找到相关场馆</view> -->
		<u-loadmore marginBottom="0" v-if="venueListData.data.records.length > 0 &&!loading "
			:status="loadmoreStatus" />
		<!-- 显示搜索状态 -->
		<!-- <div v-if="isSearching">搜索中...</div>
		<!-- 显示搜索结果 -->
		<!-- <div v-else-if="searchResults.length > 0">
			<venueList :venueList="searchResults" />
		</div> -->
		<!-- 显示没有找到相关场馆 -->
		<!-- <div v-else>没有找到相关场馆</div> -->
	</div>
</template>

<script>
	import Vue from 'vue';
	import venueListVue from "@/components/index/venueList.vue";
	import searchBoxVue from "../../components/index/search-box.vue";
	import venueTypesVue from '@/components/index/venueTypes.vue';
	import {
		getVenueList,
		getVenueTypes
	} from '@/api/index/gymtype.js';
	import {
		data,
		onLoad
	} from 'uview-ui/libs/mixin/mixin';
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";
	import {
		store
	} from '@/store/index.js';
	import {
		getLocationByIP,
		reverseGeocoding
	} from '@/api/index/tencentMapApi.js';
	export default {
		components: {
			searchBox: searchBoxVue,
			venueList: venueListVue,
			venueTypes: venueTypesVue,
		},
		data() {
			return {
				venueTypesData: [],
				getRecommend: '',
				searchKeyword: '',
				locationInfo: {
					latitude: null,
					longitude: null
				},
				venueListData: {
					data: {
						current: 1,
						size: 10,
						total: 0,
						type: undefined,
						records: []
					}
				}, // 新增场馆列表数据
				searchResults: [],
				scrollTop: 0,
				loading: true, //控制骨架屏显示
				page: {
					pageNum: 1,
					pageSize: 10
				},
				// 总数据条数
				total: 0,
				// 数据加载状态
				loadmoreStatus: "loadmore",
				//用于筛选分类的关键词
				selectedType: '',
				//用于控制加载提示显示的状态
				iconloading: false,
				// 控制下拉菜单的显示与隐藏
				isVenueTypesMenuVisible: false,
				type: undefined,
			};
		},
		onReachBottom() {
			this.getMoreVenueList();
			console.log('页面滚动到底部，触发分页加载');
		},
		// 在滑动过程实时获取现在的滚动条位置，并保存当前的滚动条位置
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		watch: {
			loadmoreStatus(newStatus) {
				console.log('loadmoreStatus 发生变化，新值为:', newStatus);
				if (newStatus === 'loadmore') {
					console.log('分页加载成功');
				} else if (newStatus === 'nomore') {
					console.log('分页加载无新数据');
				} else if (newStatus === 'error') {
					console.log('分页加载失败');
				}
			}
		},
		methods: {

			onLocationBarClick() {
				// 处理定位栏点击事件
			},
			// 获取缓存中的定位信息
			getCachedLocation() {
				const userName = uni.getStorageSync('curUser')?.userName;
				if (userName) {
					const cacheKey = `location_${userName}`;
					const cachedLocation = uni.getStorageSync(cacheKey);
					console.log('缓存中的位置信息:', JSON.stringify(cachedLocation));
					if (cachedLocation) {
						this.getRecommend = cachedLocation.recommend;
						this.locationInfo.latitude = cachedLocation.latitude;
						this.locationInfo.longitude = cachedLocation.longitude;
					}
				}
			},
			getSearchKeyword() {
				const options = this.$route.query;

				if (options.type) {
					this.type = decodeURIComponent(options.type);
					console.log('接收到的类型:', this.type, this.searchKeyword);
					this.executeSearch(this.type, this.searchKeyword);
				};
				if (options.selectedType) {
					this.selectedType = decodeURIComponent(options.selectedType);
					console.log('接收到的选中类型:', this.selectedType);
					this.executeSearch(this.selectedType);
				};
				if (options.keyword) {
					this.searchKeyword = decodeURIComponent(options.keyword);
					console.log('接收到的搜索关键词:', this.type, this.searchKeyword);
					this.executeSearch(this.type, this.searchKeyword);
				};
				// handleSearchInput(value) {
				// 	this.searchKeyword = value;
				// }
			},
			executeSearch(type, keyword = '') {
				this.loading = true; // 开始筛选，显示骨架屏
				try {
					this.getVenueListData();
				} catch (error) {
					console.error('筛选场馆数据出错:', error);
					this.errorMessage = '数据加载失败，请稍后重试'; // 显示错误提示
				}
				// if (type&&keyword) {
				// 	if (keyword) {
				// 		this.searchResults = this.venueListData.data.records.filter(venue =>
				// 			venue.type === type && venue.name && venue.name.includes(keyword)
				// 		);
				// 	} else {
				// 		this.searchResults = this.venueListData.data.records.filter(venue =>
				// 			venue.type === type
				// 		);
				// 	}
				// 	console.log('筛选后的结果:', this.searchResults);
				// } else {
				// 	if (keyword) {
				// 		this.searchResults = this.venueListData.data.records.filter(venue =>
				// 			venue.name && venue.name.includes(keyword)
				// 		);
				// 	} else {
				// 		this.searchResults = this.venueListData.data.records; // 没有选择类型和关键词时显示所有场馆
				// 	}
				// }
				this.loading = false; // 筛选完成，隐藏骨架屏
			},
			// onSearch(keyword) {
			// 		this.loading = true; // 开始筛选，显示骨架屏
			// 		if (keyword) {
			// 			this.searchResults = this.venueListData.data.records.filter(venue =>
			// 				venue.name && venue.name.includes(keyword)
			// 			);
			// 			console.log('筛选后的结果:', this.searchResults);
			// 		} else {
			// 			this.searchResults = this.venueListData.data.records; // 没有输入关键词时显示所有场馆
			// 		}
			// 		this.loading = false; // 筛选完成，隐藏骨架屏
			// 	},
			// executeSearch(type) {
			// 	this.loading = true; // 开始筛选，显示骨架屏
			// 	if (type) {
			// 		console.log('所有场馆的type:', this.venueListData.data.records.map(venue => venue.type));
			// 		this.searchResults = this.venueListData.data.records.filter(venue =>
			// 			venue.type === type
			// 			// || venue.typeName === selectedType
			// 			// && venue.typeName === type
			// 			// this.searchResults = this.venueListData.data.records.filter(venue =>
			// 			// 	venue.typeName && venue.typeName === type
			// 		);
			// 		console.log('筛选后的结果:', this.searchResults);
			// 	} else {
			// 		this.searchResults = this.venueListData.data.records; // 没有选择类型时显示所有场馆
			// 	}
			// 	this.loading = false; // 筛选完成，隐藏骨架屏
			// },
			async getLocation() {
				try {

					// 优先尝试快速获取缓存位置
					const cachedLocation = this.getCachedLocation();
					if (cachedLocation) return;

					const res = await new Promise((resolve, reject) => {
						uni.getLocation({
							type: 'wgs84',
							success: (res) => {
								resolve(res);
							},
							fail: (err) => {
								reject(err);
							}
						});
					});
					this.locationInfo = {
						latitude: res.latitude,
						longitude: res.longitude,
					};
					console.log('当前位置的纬度：', res.latitude);
					console.log('当前位置的经度：', res.longitude);

					// 调用逆地址解析函数
					try {
						const recommend = await reverseGeocoding(this, res.latitude, res.longitude);
						// 更新推荐地址
						this.recommend = recommend;
						// 存储到缓存
						const userName = uni.getStorageSync('curUser').userName;
						// console.log("userName:" + JSON.stringify(userName));
						const cacheKey = `location_${userName}`;
						let location = {
							latitude: res.latitude,
							longitude: res.longitude,
							recommend: recommend
						};
						console.log("location:" + JSON.stringify(location));
						uni.setStorageSync(cacheKey, location);
						console.log("逆地址解析成功，缓存键:", cacheKey);
					} catch (error) {
						console.error('逆地址解析失败:', error);
						// uni.showToast({
						// 	title: '逆地址解析失败',
						// 	icon: 'none'
						// });
					}
				} catch (err) {
					console.error('获取位置失败，尝试通过 IP 获取', err);
					try {
						const location = await getLocation();
						if (location) {
							this.locationInfo = {
								latitude: location.lat,
								longitude: location.lng
							};
							console.log('通过 IP 获取的位置 - 纬度：', location.lat);
							console.log('通过 IP 获取的位置 - 经度：', location.lng);
						} else {
							uni.showToast({
								title: '通过 IP 获取位置失败',
								icon: 'none'
							});
						}
					} catch (ipErr) {
						console.error('通过 IP 获取位置失败', ipErr);
						// uni.showToast({
						// 	title: '获取位置失败',
						// 	icon: 'none'
						// });
					}
				}
			},
			clearResult() {
				this.venueListData.data.records = [];
				this.page.pageNum = 1;
				this.loadmoreStatus = "loadmore";
				this.loading = true;
			},
			/**
			 * 发起场馆列表请求
			 */
			async fetchVenueList() {
				try {
					return await getVenueList({
						current: this.page.pageNum - 1,
						size: this.page.pageSize,
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude,
						km: 1000,
						name: this.searchKeyword,
						type: this.type,
						// type:0,
					});
				} catch (error) {
					console.error('获取场馆列表数据失败:', error);
					this.loading = false; // 隐藏骨架屏
					throw error;
				}
			},
			async getVenueListData() {
				this.loading = true;
				this.loadmoreStatus = "loading";
				try {
					console.log('传递的经纬度:', {
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude
					});
					const venueListRes = await getVenueList({
						// venueListReqDTO: {
						// current: 0,
						current: this.page.pageNum - 1,
						// size: 100,
						name: this.searchKeyword,
						// typeName: this.selectedType,
						// 修改为 page.pageSize
						size: this.page.pageSize,
						// name: '',
						type: this.type,
						latitude: this.locationInfo.latitude,
						longitude: this.locationInfo.longitude,
						km: 1000,
						// status: null
						// }
					});
					// const venueListRes = await getVenueList({
					// 	// venueListReqDTO: {
					// 		current: 0,
					// 		size: 10,
					// 		// name: '',
					// 		// type: null,
					// 		latitude: 34.131,
					// 		longitude: 108.8,
					// 		km: 10,
					// 		// status: null
					// 	// }
					// });
					// console.log('场馆查询数据:', JSON.stringify(venueListRes));
					// if (this.page.pageNum === 1) {
					// 	this.venueListData.data.records = venueListRes.data.records;
					// 	this.searchResults = venueListRes.data.records;
					// } else {
					// 	this.venueListData.data.records = this.venueListData.data.records.concat(venueListRes.data
					// 		.records);
					// 	this.searchResults = this.searchResults.concat(venueListRes.data.records);
					// }
					// this.total = venueListRes.data.total;
					// if (this.searchResults.length >= this.total) {
					// 	this.loadmoreStatus = "nomore";
					// } else {
					// 	this.loadmoreStatus = "loadmore";
					// }
					this.venueListData.data.records = venueListRes.data.records;
					this.total = venueListRes.data.total;
					this.searchResults = this.venueListData.data.records; // 更新 searchResults 数组
					this.total = searchResults;
					// console.log('场馆列表数据:', JSON.stringify(this.venueListData.data.records));
					// this.venueListData.records = venueListRes.data.records;
					// 如果有筛选条件，进行筛选
					// if (this.selectedType) {
					// 	this.executeSearch(this.selectedType);
					// }
					// if (this.searchKeyword) {
					// 	this.onSearch(this.searchKeyword);
					// }
					this.loading = false; // 更新加载状态
					this.loadmoreStatus = "loadmore";
				} catch (error) {
					// console.error('获取场馆列表数据失败:', error);
					this.loadmoreStatus = "error";
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 获取下一页的场馆信息
			 */
			async getMoreVenueList() {
				if (this.venueListData.data.records.length >= this.total) {
					// 没有更多数据了
					this.loadmoreStatus = "nomore";
				} else {
					if (!this.loading) {
						this.page.pageNum++;
						// 显示正在加载
						this.loadmoreStatus = "loading";
						// 修改后
						try {
							const newData = await this.fetchVenueList();
							this.venueListData.data.records = this.venueListData.data.records
								.concat(newData.data
									.records);
							this.searchResults = this.venueListData.data.records; //更新下一分页的数据
							this.loadmoreStatus = newData.data.records.length > 0 ? "loadmore" :
								"nomore";
						} catch (error) {
							console.error('获取下一页场馆列表数据失败:', error);
							this.loadmoreStatus = "error";
						}
					}
				}
				// if (this.venueListData.data.records.length >= this.total) {
				// 	// 没有更多数据了
				// 	this.loadmoreStatus = "nomore";
				// 	return;
				// } else {
				// 	if (!this.loading) {
				// 		this.page.pageNum++;
				// 		// 显示正在加载
				// 		this.loadmoreStatus = "loading";
				// 		// 修改后
				// 		try {
				// 			const newVenueListRes = await this.fetchVenueList();
				// 			// 合并新数据和已有数据
				// 			this.venueListData.data.records = this.venueListData.data.records.concat(
				// 				newVenueListRes.data.records);
				// 			this.total = newVenueListRes.data.total;
				// 根据当前筛选条件重新筛选数据
				// if (this.type && this.searchKeyword) {
				//     // 若 type 和 keyword 都存在，传递这两个参数进行筛选
				//     this.executeSearch(this.type, this.searchKeyword);
				// } else if (this.type) {
				//     // 若只有 type 存在，传递 type 进行筛选，keyword 默认为空
				//     this.executeSearch(this.type, ''); 
				// } else if (this.searchKeyword) {
				//     // 若只有 keyword 存在，type 传空，传递 keyword 进行筛选
				//     this.executeSearch('', this.searchKeyword); 
				// } else {
				//     // 若 type 和 keyword 都不存在，显示所有场馆数据
				//     this.searchResults = this.venueListData.data.records;
				// }    
				// // 根据当前筛选条件重新筛选数据
				// if (this.type) {
				// 	this.executeSearch(this.type);
				// } else if (this.searchKeyword) {
				// 	this.executeSearch(this.searchKeyword);
				// } else {
				// 	this.searchResults = this.venueListData.data.records;
				// }

				// 		if (this.venueListData.data.records.length >= this.total) {
				// 			this.loadmoreStatus = 'nomore';
				// 		} else {
				// 			this.loadmoreStatus = 'loadmore';
				// 		}
				// 	} catch (error) {
				// 		console.error('获取更多场馆列表数据失败:', error);
				// 		this.loadmoreStatus = 'error';
				// 		this.page.pageNum--;
				// 	}
				// }
				// try {
				// 	const venueListRes = await this.fetchVenueList();
				// 	if (venueListRes.data.records.length > 0) {
				// 		this.venueListData.data.records = this.venueListData.data.records.concat(venueListRes.data
				// 			.records);
				// 		this.searchResults = this.venueListData.data.records;
				// 		this.loadmoreStatus = "loadmore";
				// 	} else {
				// 		this.loadmoreStatus = "nomore";
				// 	}
				// } catch (error) {
				// 	console.error('分页加载场馆列表数据失败:', error);
				// 	this.loadmoreStatus = "error";
				// 	this.page.pageNum--;
				// }
				// },

			},
			// 控制下拉菜单的显示与隐藏
			toggleVenueTypesMenu() {
				this.isVenueTypesMenuVisible = !this.isVenueTypesMenuVisible;
			},
			// onSelectType(type) {
			// 	this.type = type;
			// 	this.clearResult();
			// 	this.executeSearch(type);
			// 	this.loading = true; // 显示加载状态
			// 	this.getVenueListData().then(() => {
			// 		this.loading = false; // 数据加载完成，隐藏加载状态
			// 	});
			// 	// this.getVenueListData();
			// 	// this.isVenueTypesMenuVisible = false;
			// },
		},
		// async onLoad() {
		// 	await this.getLocation();
		// 	await this.getVenueListData();
		// 	this.getSearchKeyword();
		// },
		async created() {
			try {
				// 并行发起不依赖的请求
				const [venueTypesRes, location] = await Promise.all([
					// 发起请求获取场地类型和场馆列表数据
					getVenueTypes(),
					this.getLocation().catch(e => console.error('获取位置失败', e)) // 即使位置获取失败也不阻塞
				]);
				this.venueTypesData = venueTypesRes.data;
				this.getSearchKeyword();
				await this.getVenueListData();
				// console.log('场馆查询数据:',JSON.stringify(venueListRes.data));
				// 假设场馆列表数据直接是一个数组
				// this.venueListData = venueListRes.data;
			} catch (error) {
				console.error('获取数据失败:', error);
				this.loading = false; // 数据加载完成，隐藏骨架屏
			}
		}
	}
</script>

<style lang="scss">
	.search-box {
		padding: 10px 16px;
		background-color: #f7f7f9;
		border-top-right-radius: 20px;
		border-top-left-radius: 20px;

		.search-input {
			background-color: white;
			margin-top: 5px;
			border-radius: 30px;
			border: 2px solid #4A90E2;
			display: flex;
			align-items: center;
			padding: 5px 7px 5px 12px;

			input {
				flex: 1;
				margin: 0 10px;
			}

			.search-btn {
				background-color: #87CEEB;
				color: white;
				border-radius: 32px;
				border: 0;
				padding: 0 13px;
				font-size: 14px;
				height: 30px;
				line-height: 30px;
			}
		}
	}

	.searchPage {
		background-color: #f7f7f9;
		min-height: 100vh;
		/* 最小高度为视口高度 */
		width: 100%;
		/* 宽度为 100% */
		box-sizing: border-box;
		/* 确保内边距和边框包含在宽度和高度内 */


		.location-bar {
			background-color: #f7f7f9;
			padding: 10px 16px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: black;

			.location {
				display: flex;
				align-items: center;
				gap: 8px;
				font-size: 14px;

			}

			.type {
				display: flex;
				justify-content: space-between;
				align-items: center;
				min-width: fit-content;
				/* 设置最小宽度为内容宽度 */
			}

			.type text {
				white-space: nowrap;
				color: gray;
				font-size: 14px;
				margin-right: 3px;
			}
		}

		.venue-types-menu {
			position: absolute;
			top: 100px;
			/* 根据实际情况调整 */
			left: 0;
			right: 0;
			background-color: white;
			z-index: 1;
			border-bottom: 1px solid #ccc;
		}

		.skeleton-screen {
			background-color: #fff;
			/* // border-radius: 8px; //会给骨架屏添加圆角属性 */
			padding: 15px;
			padding-right: 20px;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}

		.full-screen {
			position: relative;
			padding-right: 20px;
			top: 0;
			left: 0;
			width: 100%;
			// height: 100%;
			height: auto;
			/* 让高度根据内容自动调整 */
			min-height: 100px;
			/* 设置最小高度 */
			z-index: 99;
			/* 确保骨架屏在最上层 */
		}
	}
</style>